import linecache
from os import path
import os
import time
import logging
import datetime

_log = logging.getLogger('clearlog')


# 删除日志
class ClearLogManage:

    @classmethod
    def clearLog(self, config=None):
        self.logMaxSpace = config["logMaxSpace"]
        self.logListPath = config['logListPath']
        # 遍历日志文件夹
        for item in self.logListPath:
            self.scanLog(item)

    # 递归查找日志文件
    @classmethod
    def scanLog(self, filePath):
        logFileList = os.listdir(filePath)
        for logFilePath in logFileList:
            if path.isdir(filePath + path.sep + logFilePath):
                self.scanLog(filePath + path.sep + logFilePath)
            else:
                # 获取每个日志文件
                logFile: str = filePath + path.sep + logFilePath
                fileSize = path.getsize(filePath + path.sep + logFilePath)
                self.deleteLog(logFile, fileSize / 1024 / 1024)

    # 删除日志
    @classmethod
    def deleteLog(self, logFile, fileSize):
        if fileSize >= self.logMaxSpace:
            _log.info(f"{logFile} 占用大小 {fileSize} M 删除成功")
            os.remove(logFile)
